export default class PlayVoice {
  private static _instance: PlayVoice | null = null
  private audioQueue: string[] = []
  private audioList: string[] = []
  private audioElement: HTMLAudioElement
  private isPlaying = false

  private constructor() {
    this.audioElement = new Audio()
  }

  public static get instance(): PlayVoice {
    if (!this._instance) {
      this._instance = new PlayVoice()
    }
    return this._instance
  }

  public play(url: string) {
    this.audioQueue.push(url)
    this.audioList.push(url)
    // 如果没有正在播放的音频，则开始播放队列中的音频
    if (!this.isPlaying) {
      // this.playNextFromQueue();
    }
  }

  public getAudioQueue(): string[] {
    return this.audioList
  }

  private async playNextFromQueue() {
    // 如果队列中没有音频，则停止播放
    if (this.audioQueue.length <= 0) {
      this.stop()
      return
    }

    try {
      await this.playAudio(this.audioQueue[0]) // 播放音频
    } catch (error) {
      this.stop()
      console.error("Error playing audio:", error)
    }
  }

  private playAudio(url: string): Promise<void> {
    this.audioQueue.shift() // 移除数组的第一项
    return new Promise<void>((resolve, reject) => {
      this.isPlaying = true
      this.audioElement.src = url
      this.audioElement.play()
      this.audioElement.onerror = (error) => {
        this.stop()
        reject(error)
      }
      this.audioElement.onended = () => {
        this.isPlaying = false
        this.playNextFromQueue()
        resolve()
      }
    })
  }

  public stop(): void {
    this.audioElement.pause() // 暂停播放
    this.audioQueue = []
    this.audioElement.currentTime = 0 // 将当前播放时间设置为 0
    this.isPlaying = false
    this.audioElement = null as any // 销毁实例
  }
}
